package data 

import (
	"strings"
	"time"
	
	"github.com/globalsign/mgo"
)

type MongoUtil struct {
	dbName 		string 
	collName 	string 
	session 	*mgo.Session
}

type Mu MongoUtil //做一个alias，才能设置依赖

func NewMu(cfg *MongoCfg) *Mu {
	return *Mu(NewMongoUtil(cfg))
}

func NewMongoUtil(cfg *MongoCfg) *MongoUtil {
	// db collection 从配置读取
	addrs := strings.Split(cfg.Addrs, ",")
	dialInfo := &mgo.DialInfo{
		Addrs:    addrs,
		Timeout:  50 * time.Second,
		Source:   cfg.Source,
		Username: cfg.User,
		Password: cfg.Pass,
	}
	s, err := mgo.DialWithInfo(dialInfo)
	if err != nil {
		panic("create session error " + err.Error())
	}
	
	return &MongoUtil{
		dbName: cfg.DbName,
		collName: cfg.Coll,
		session: s,
	}	
}

func (m* MongoUtil) connect(db, collection string) (*mgo.Session, *mgo.Collection) {
	s := m.session
	c := s.DB(db).C(collection)
	return s, c
}

func (m* MongoUtil) FindOne(query, result interface{}) error {
	ms, c := m.connect(m.dbName, m.collName)
	defer ms.Close()
	return c.Find(query).One(result)
}

func (m* MongoUtil) InsertOne(query interface{}) error {
	ms, c := m.connect(m.dbName, m.collName)
	defer ms.Close()
	return c.Insert(query)
}

//释放资源
func (m* MongoUtil) Close() {
	m.session.Close()
}

